package com.gitee.wsl.jvm.struct.generator

//package me.leon.hash.keygen

import com.gitee.wsl.struct.generator.ByteArrayGenerator
import com.gitee.wsl.struct.generator.Generator
import com.gitee.wsl.struct.generator.StringGeneratorWithLength
import java.security.SecureRandom


/**
 * A KeyGenerator that uses [SecureRandom] to generate byte array-based keys.
 *
 * No specific provider is used for the `SecureRandom`, so the platform default will be used.
 *
 * @author Keith Donald
 */
class SecureRandomBytesKeyGenerator
@JvmOverloads
constructor(val keyLength: Int = DEFAULT_KEY_LENGTH) : ByteArrayGenerator {
    private val random = SecureRandom()

    companion object {
        private const val DEFAULT_KEY_LENGTH = 8
        val instance = SecureRandomBytesKeyGenerator()
    }

    override fun invoke(): ByteArray {
        val bytes = ByteArray(keyLength)
        random.nextBytes(bytes)
        return bytes
    }
}

fun Generator.secureRandom() = SecureRandomBytesKeyGenerator.instance
fun Generator.secureRandom(keyLength: Int) = SecureRandomBytesKeyGenerator(keyLength)
fun Generator.base64Random(): StringGeneratorWithLength {
    return {length-> java.util.Base64.getEncoder().encode(SecureRandomBytesKeyGenerator(length).invoke()).toString()}
}